<template>
  <div class="h-full w-full p-5">
    <div class="card-box h-full">
      <div class="product-list-container min-h-full">
        <!-- 页面标题和操作区 -->
        <div class="page-header">
          <h1 class="page-title">产品管理</h1>
          <div class="actions">
            <el-button
              type="primary"
              @click="openTimeSettingDialog"
              class="setting-btn"
            >
              <i class="el-icon-setting"></i> 设置可预约时间
            </el-button>
            <el-button
              type="primary"
              @click="handleGoto(undefined)"
              class="add-btn"
            >
              <i class="el-icon-plus"></i> 新增产品
            </el-button>
          </div>
        </div>

        <!-- 筛选区 -->
        <el-card class="filter-card">
          <div class="filter-group">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索产品名称"
              clearable
              class="search-input"
              @keyup.enter="handleSearch"
              @clear="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch">
                  <IconifyIcon icon="material-symbols:search" />
                </el-button>
              </template>
            </el-input>
          </div>
        </el-card>

        <!-- 产品列表 -->
        <el-card class="table-card">
          <el-table
            :data="tableData"
            border
            stripe
            :loading="tableLoading"
            empty-text="暂无产品数据"
            style="width: 100%"
          >
            <el-table-column
              type="index"
              label="序号"
              width="80"
              align="center"
            >
            </el-table-column>
            <el-table-column label="产品图片" width="100" align="center">
              <template #default="scope">
                <img
                  :src="scope.row.imageUrl"
                  alt="产品图片"
                  style="
                    width: 60px;
                    height: 60px;
                    object-fit: cover;
                    border-radius: 4px;
                  "
                />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="产品名称" align="center" />
            <el-table-column prop="price" label="价格" align="center">
              <template #default="scope">
                {{ `${scope.row.price}元/小时` }}
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.state === 0 ? 'success' : 'info'">
                  {{ scope.row.state === 0 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间"
              align="center"
              width="200"
            />
            <el-table-column
              prop="updateTime"
              label="更新时间"
              align="center"
              width="200"
            />
            <el-table-column label="操作" width="280" align="center">
              <template #default="scope">
                <el-button type="primary" @click="handleGoto(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  :type="scope.row.state === 0 ? 'warning' : 'success'"
                  @click="handleChangeStatus(scope.row)"
                >
                  {{ scope.row.state === 0 ? '禁用' : '启用' }}
                </el-button>
                <el-popconfirm
                  title="确定删除这个产品吗？"
                  @confirm="handleDelete(scope.row.id)"
                >
                  <template #reference>
                    <el-button type="danger">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="totalProducts"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </el-card>

        <!-- 可预约时间设置对话框 -->
        <el-dialog
          v-model="timeSettingVisible"
          title="设置可预约时间"
          width="1000px"
          class="time-setting-dialog"
        >
          <div class="time-grid">
            <!-- 表头：时间点 -->
            <div class="time-grid-header time-grid-cell header-corner"></div>
            <div
              v-for="hour in availableHours"
              :key="hour"
              class="time-grid-header time-grid-cell"
            >
              {{ formatHourLabel(hour) }}
            </div>

            <!-- 每天的时间选择行 -->
            <template
              v-for="(config, index) in timeSettingForm.reservationConfig"
              :key="config.sunday"
            >
              <div class="time-grid-row-label time-grid-cell">
                {{ weekDays.find((d) => d.value === config.sunday)?.label }}
              </div>
              <div
                v-for="hour in availableHours"
                :key="hour"
                class="time-grid-cell"
                @click="handleTimeToggle(config, hour)"
              >
                <div
                  class="time-slot"
                  :class="{ selected: config.selectedTimes[hour] }"
                ></div>
              </div>
            </template>
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="timeSettingVisible = false">取消</el-button>
              <el-button type="primary" @click="saveTimeSetting">{{
                isTimeSlotExist ? '更新' : '保存'
              }}</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import {
  ElButton,
  ElCard,
  ElInput,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElMessage,
  ElPopconfirm,
  ElDialog,
  ElTag,
} from 'element-plus';
import { IconifyIcon } from '@vben/icons';
import {
  getProductList,
  deleteProduct,
  getApptTimeSlotList,
  updateProductStatus,
  type productApi,
  addApptTimeSlotList,
} from '#/api/product';

const router = useRouter();

// 状态管理
const searchKeyword = ref('');
const tableLoading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const totalProducts = ref(0);
const tableData = ref<productApi.listItem[]>([]);
// 监听pageSize变化，重置currentPage为1并重新加载数据
watch(pageSize, (newSize) => {
  currentPage.value = 1; // 页码重置为1
});

// 监听currentPage变化，重新加载数据
watch(currentPage, (newPage) => {
  loadProducts();
});

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1; // 搜索时重置页码
  loadProducts();
};

const handleGoto = (row?: productApi.listItem | undefined) => {
  if (row && row.id) {
    router.push(`/product/listDetail/${row.id}`);
  } else {
    router.push('/product/listDetail');
  }
};
// 加载产品数据
const loadProducts = async () => {
  tableLoading.value = true;
  try {
    const {
      data: { list, total },
    } = await getProductList({
      name: searchKeyword.value,
      pageNum: currentPage.value, // 传递当前页码
      pageSize: pageSize.value, // 传递每页条数
    });
    totalProducts.value = Number(total);
    tableData.value = list;
  } catch (error) {
    console.error('加载产品失败:', error);
    tableData.value = [];
    totalProducts.value = 0;
    ElMessage.error('加载产品数据失败');
  } finally {
    tableLoading.value = false;
  }
};

// 删除相关方法
const handleDelete = async (id: string) => {
  try {
    const data = await deleteProduct(id);
    if (data.code === 200) {
      ElMessage.success('产品删除成功');
      loadProducts();
    } else {
      ElMessage.error('产品删除失败：' + (data.message || '未知错误'));
    }
  } catch (error) {
    console.error('删除产品失败:', error);
    ElMessage.error('删除产品失败');
  }
};

// 添加更改状态方法
const handleChangeStatus = async (row: productApi.listItem) => {
  try {
    const data = await updateProductStatus(row.id);
    if (data.code === 200) {
      ElMessage.success(`${row.state === 0 ? '禁用' : '启用'}产品成功`);
      loadProducts();
    } else {
      ElMessage.error(
        `${row.state === 0 ? '禁用' : '启用'}产品失败：` +
          (data.message || '未知错误'),
      );
    }
  } catch (error) {
    console.error(`${row.state === 0 ? '禁用' : '启用'}产品失败:`, error);
    ElMessage.error(`${row.state === 0 ? '禁用' : '启用'}产品失败`);
  }
};

// 可预约时间设置相关
const timeSettingVisible = ref(false);
const isTimeSlotExist = ref(false); // 标识是否存在预约时间配置

const weekDays = [
  { label: '周一', value: 1 },
  { label: '周二', value: 2 },
  { label: '周三', value: 3 },
  { label: '周四', value: 4 },
  { label: '周五', value: 5 },
  { label: '周六', value: 6 },
  { label: '周日', value: 7 },
];

const availableHours = Array.from({ length: 17 }, (_, i) => i + 6); // 6点到23点

// 修改表单结构以匹配后端要求的数据格式
const timeSettingForm = reactive({
  reservationConfig: weekDays.map((day) => ({
    sunday: day.value,
    timeRangeList: [] as { startTime: string; endTime: string }[],
    selectedTimes: {} as Record<number, boolean>, // 用于跟踪每个时间段的选择状态
  })),
});

// 格式化小时标签
const formatHourLabel = (hour: number) => {
  return `${hour.toString().padStart(2, '0')}:00-${(hour + 1).toString().padStart(2, '0')}:00`;
};

// 格式化小时值
const formatHour = (hour: number) => {
  return {
    startTime: `${hour.toString().padStart(2, '0')}:00`,
    endTime: `${(hour + 1).toString().padStart(2, '0')}:00`,
  };
};

// 处理时间选择切换
const handleTimeToggle = (config: any, hour: number) => {
  const currentValue = config.selectedTimes[hour] || false;
  const newValue = !currentValue;
  config.selectedTimes[hour] = newValue;

  if (newValue) {
    // 添加时间段
    config.timeRangeList.push(formatHour(hour));
  } else {
    // 移除时间段
    const index = config.timeRangeList.findIndex(
      (range: { startTime: string }) =>
        range.startTime === `${hour.toString().padStart(2, '0')}:00`,
    );
    if (index !== -1) {
      config.timeRangeList.splice(index, 1);
    }
  }
};

// 修改打开时间设置对话框的方法，获取现有配置
const openTimeSettingDialog = async () => {
  timeSettingVisible.value = true;

  try {
    // 获取现有的预约时间配置
    const res = await getApptTimeSlotList();
    console.log('获取可预约时间列表:', res);

    if (res.data && res.data.length > 0) {
      isTimeSlotExist.value = true;

      // 解析后端返回的数据并设置默认值
      res.data.forEach((item: productApi.getAllApptTimeSlotListResultItem) => {
        // 找到对应星期的配置项
        const config = timeSettingForm.reservationConfig.find(
          (c) => c.sunday === item.sunday,
        );

        if (config) {
          // 解析apptTimeSlot JSON字符串
          let timeSlots: { startTime: string; endTime: string }[] = [];
          try {
            timeSlots = JSON.parse(item.apptTimeSlot);
          } catch (e) {
            console.error('解析apptTimeSlot失败:', e);
            return;
          }

          // 清空原有数据
          config.timeRangeList = [];
          config.selectedTimes = {};

          // 设置新的时间段
          timeSlots.forEach((slot: { startTime: string; endTime: string }) => {
            const startHour = parseInt(
              slot.startTime.split(':')[0] as string,
              10,
            );
            console.log('startHour:', startHour);
            config.selectedTimes[startHour] = true;
            config.timeRangeList.push({
              startTime: slot.startTime,
              endTime: slot.endTime,
            });
          });
        }
      });
    } else {
      // 如果没有数据，则初始化为空
      isTimeSlotExist.value = false;
      timeSettingForm.reservationConfig.forEach((config) => {
        config.timeRangeList = [];
        config.selectedTimes = {};
      });
    }
  } catch (error) {
    console.error('获取预约时间配置失败:', error);
    ElMessage.error('获取预约时间配置失败');

    // 出错时也初始化为空
    timeSettingForm.reservationConfig.forEach((config) => {
      config.timeRangeList = [];
      config.selectedTimes = {};
    });
  }
};

const saveTimeSetting = async () => {
  // 排除selectedTimes字段
  const submitData = timeSettingForm.reservationConfig.map((config) => ({
    sunday: config.sunday,
    timeRangeList: config.timeRangeList,
  }));

  console.log('提交的时间设置:', submitData);

  try {
    const data = await addApptTimeSlotList(submitData);
    console.log('保存结果:', data);
    if (data.code === 200) {
      ElMessage.success('可预约时间设置已保存');
      timeSettingVisible.value = false;
      // 更新状态
      isTimeSlotExist.value = true;
    } else {
      ElMessage.error(
        '可预约时间设置保存失败：' + (data.message || '未知错误'),
      );
    }
  } catch (error) {
    console.error('保存预约时间配置失败:', error);
    ElMessage.error('可预约时间设置保存失败');
  }
};

// 页面加载时获取数据
loadProducts();
</script>

<style scoped lang="scss">
.product-list-container {
  padding: 20px;
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    .page-title {
      font-size: 20px;
      font-weight: 600;
      margin: 0;
    }
    .actions {
      display: flex;
      gap: 10px;
    }
  }
  .pagination-container {
    margin-top: 16px;
    text-align: right;
  }

  .filter-card {
    margin-bottom: 20px;
    .filter-group {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      align-items: center;
      .search-input {
        width: 300px;
      }
    }
  }
}

// 时间设置对话框样式
.time-setting-dialog {
  .time-grid {
    display: grid;
    grid-template-columns: 80px repeat(17, 1fr);
    gap: 2px;
    max-height: 60vh;
    overflow-y: auto;

    .time-grid-cell {
      padding: 8px;
      text-align: center;
      border-radius: 4px;
    }

    .header-corner {
      background-color: #f5f7fa;
    }

    .time-grid-header {
      background-color: #f5f7fa;
      font-weight: bold;
      font-size: 12px;
      padding: 10px 5px;
    }

    .time-grid-row-label {
      background-color: #f5f7fa;
      font-weight: bold;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .time-slot {
      width: 100%;
      height: 30px;
      background-color: #e4e7ed;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.2s;

      &:hover {
        background-color: #d2d5dc;
      }

      &.selected {
        background-color: #409eff;

        &:hover {
          background-color: #337ecc;
        }
      }
    }
  }
}
</style>
